<template>
  <!-- MembershipInfo 申请表单 -->
  <PageContainer>
    <view class="container">
      <FullLoading :fullLoading="isFullLoading" />
      <Header title="申请入会" v-if="isFinish === IsFinishEnum.TERMINATION" />
      <Tabs v-model="currentTab" :data="dataList" v-else>
        <Header title="申请表单" :is-box-shadow="false">
          <TabNav tabBarColor="#ef833a" />
        </Header>
        <template v-for="v in dataList" :key="v.id">
          <TabsItem :name="v.name" :value="v.id" :disabled="v.id !== currentTab"></TabsItem>
        </template>
      </Tabs>
      <template v-if="isShowStatus">
        <TResult
          :types="(status?.type as 'success' | 'error' | 'waiting')"
          :title="status?.text"
          :content="isFinish === IsFinishEnum.TERMINATION && remark ? `原因：${remark}` : ''"
          :cancel-text="isFinish !== IsFinishEnum.DONE ? '联系审核人员' : ''"
          :confirm-text="status.submitText"
          @cancel="openContactModal"
          @confirm="status.submitFnc"
        />
        <FixedCode />
      </template>
      <view v-else class="form-container">
        <ApplyForm
          v-if="apiIsInit"
          :stage-id="currentTab"
          :applicant-type="id"
          :current-data="holdData || currentData"
          :btn-group-options="btnGroupOptions"
          @on-submit="onSubmit"
          @on-load="onFormload"
          @on-change="onChange"
        />
      </view>

      <ContactReviewer
        :popupShow="contactPopupShow"
        :level="currentTab"
        @close="closeContactModal"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  MembershipInfo  申请表单 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import { computed, reactive, ref, unref } from 'vue';
  import { onLoad } from '@/router';
  import {
    type CustomFormGetStageListResult,
    type customFormUserAnswerList,
  } from '@/api/membership/types';
  import {
    memberApply,
    customFormGetStageList,
    memberApplyFormAdd,
    updateAuditStatus,
  } from '@/api/membership';
  import FullLoading from '@/components/FullLoading/index.vue';
  import { AuditStatusEnum, IsFinishEnum, PaymentStatusEnum } from '@/enums/membershipEnum';
  import { type fieldObj, handleField } from './components/conf';
  import ApplyForm from './applyForm.vue';
  import { isArray } from '@/utils/is';
  import { redirectTo } from '@/router';
  import ContactReviewer from '../awaitPay/components/contactReviewer.vue';
  import { toSelectiveType as dynamicToSelectiveType } from '@/utils/dynamicConfig';
  import { type OnchangeArgument } from '@/components/Form/types';
  import { type CardBottomBtnsOptions } from '@/components/TButtonGroup/types';
  import { getHoldData, setHoldData } from '@/utils/hold';
  import { Toast, authOfficialAccount } from '@/utils';
  import { removeHoldDataApi } from '@/api/hold';
  import TResult from '@/components/TResult/index.vue';
  import FixedCode from '@/components/OfficialAccount/fixedCode.vue';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { IsOfficialAccountEnum } from '@/enums/loginEnum';

  const { userInfo } = useUserStoreWithOut();
  const id = ref();
  const currentTab = ref();
  const dataList = ref<CustomFormGetStageListResult[]>([]);
  const isFullLoading = ref(true);
  const currentData = ref<customFormUserAnswerList[]>([]);
  const remark = ref();
  const apiIsInit = ref(false);

  const btnGroupOptions = reactive<CardBottomBtnsOptions>({
    submit: {
      text: '提交',
    },
    custom: {
      text: '暂存',
      clickFn: (vals) => {
        const data = getSubmitData(vals, true);
        setHoldData({
          businessType: 'membership',
          businessId: getBusinessId(),
          content: data,
        }).then(() => Toast('暂存成功', 'none', 1500));
      },
    },
  });

  const getBusinessId = (formStageId?: number) =>
    `${unref(id)}_${formStageId || unref(currentTab) || unref(dataList)[0].id}`;

  onLoad<'MembershipInfo'>((op) => {
    id.value = op.id;
    __int();
  });

  const holdData = ref();
  async function __int() {
    try {
      await getTabList();
      await getMemberApply();
    } catch (err) {
      console.log(err);
      console.error('数据加载错误...');
    } finally {
      if (
        auditStatus.value === AuditStatusEnum.CHECKPENDING ||
        isFinish.value === IsFinishEnum.DONE ||
        isFinish.value === IsFinishEnum.TERMINATION
      ) {
        isFullLoading.value = false;
      }
    }
  }

  function onFormload() {
    isFullLoading.value = false;
  }

  /** 获取阶段列表 */
  async function getTabList() {
    const r = await customFormGetStageList(id.value);
    if (!currentTab.value) currentTab.value = r[0].id;
    const stageId = currentTab.value;
    if (
      auditStatus.value === AuditStatusEnum.AUDITED &&
      isFinish.value === IsFinishEnum.UNFINISHED
    ) {
      const index = r.findIndex((v) => v.id === stageId);
      index && index !== -1 && (currentTab.value = r[index].id);
      auditStatus.value = null;
    }
    return (dataList.value = r);
  }

  const auditStatus = ref();
  const isFinish = ref();
  const paymentStatus = ref();
  const companyId = ref<number>();

  /** 获取我已填写的内容 */
  async function getMemberApply() {
    const r = await memberApply();
    const hData = await getHoldData<{ customFormItem: { answerList: customFormUserAnswerList[] } }>(
      {
        businessType: 'membership',
        businessId: getBusinessId(r?.formStageId),
      },
    );
    const answerList = hData?.customFormItem?.answerList;
    if (hData && answerList && answerList.length > 0) {
      holdData.value = answerList;
    }
    if (r) {
      currentTab.value = r.formStageId;
      auditStatus.value = r.auditStatus;
      companyId.value = r.companyId;
      isFinish.value = r.isFinish;
      paymentStatus.value = r.paymentStatus;
      currentData.value = r.customFormUserAnswerList;
      remark.value = r.remark;
    }
    apiIsInit.value = true;
  }

  const isShowStatus = computed(() => {
    return (
      unref(auditStatus) === AuditStatusEnum.CHECKPENDING ||
      unref(isFinish) === IsFinishEnum.DONE ||
      unref(isFinish) === IsFinishEnum.TERMINATION
    );
  });

  const status = computed(() => {
    if (paymentStatus.value === PaymentStatusEnum.ALREADYPAYCOST) {
      return {
        type: 'success',
        text: '已缴费',
        submitText: '查看详情',
        submitFnc: () => {
          dynamicToSelectiveType({
            linkUrl: 'selectiveType',
            isRedirectTo: true,
          });
        },
      };
    }
    if (
      isFinish.value === IsFinishEnum.DONE &&
      paymentStatus.value === PaymentStatusEnum.NOTPAYCOST
    ) {
      return {
        type: 'success',
        text: '已通过',
        submitText: '立即缴费',
        submitFnc: () => {
          dynamicToSelectiveType({
            linkUrl: 'selectiveType',
            isRedirectTo: true,
          });
        },
      };
    } else if (
      isFinish.value === IsFinishEnum.DONE &&
      paymentStatus.value === PaymentStatusEnum.DUE
    ) {
      return {
        type: 'success',
        text: '已通过',
        submitText: '缴费详情',
        submitFnc: () => {
          dynamicToSelectiveType({
            linkUrl: 'selectiveType',
            isRedirectTo: true,
          });
        },
      };
    } else if (isFinish.value === IsFinishEnum.TERMINATION) {
      return {
        type: 'error',
        text: '终止审核',
        submitText: '重新申请入会',
        submitFnc: () => {
          updateAuditStatus().then(() => {
            redirectTo({ name: 'selectiveType' });
          });
        },
      };
    } else {
      return {
        type: 'waiting',
        text: '审核中',
        submitText: '刷新审核状态',
        submitFnc: () => {
          refreshStatus();
        },
      };
    }
  });

  function onChange(op: OnchangeArgument) {
    const { val } = op;
    if (val) {
      companyId.value = val?.id;
    }
  }

  function getSubmitData(vals: { [x: string | number]: any }, IsContentStr: boolean = false) {
    const answerList = [];
    for (const k in vals) {
      const { stageId, groupId, id } = handleField(currentTab.value, k) as fieldObj;
      let content = vals[k];
      if (!isArray(content)) content = content.toString().split(',');
      answerList.push({
        formItemId: id,
        formStageId: stageId,
        formGroupId: groupId,
        content: IsContentStr ? JSON.stringify(content) : content,
      });
    }
    return {
      applyTemplateId: id.value,
      formStageId: currentTab.value,
      companyId: companyId.value,
      customFormItem: {
        answerList,
      },
    };
  }

  const onSubmit = async (vals: { [x: string | number]: any }) => {
    const data = getSubmitData(vals);
    await removeHoldDataApi({
      businessType: 'membership',
      businessId: getBusinessId(),
    });
    memberApplyFormAdd(data).then(async (r) => {
      try {
        await authOfficialAccount();
      } catch (error) {}
      if (r.auditStatus === AuditStatusEnum.AUDITED) {
        apiIsInit.value = false;
        currentTab.value = void 0;
        auditStatus.value = void 0;
        isFinish.value = void 0;
        paymentStatus.value = void 0;
        refreshStatus();
      } else {
        auditStatus.value = r.auditStatus;
        isFinish.value = r.isFinish;
        paymentStatus.value = r.paymentStatus;
      }
    });
  };

  /** 刷新审核状态 */
  function refreshStatus() {
    isFullLoading.value = true;
    __int();
  }

  // 打开和关闭联系审核人员
  const contactPopupShow = ref(false);
  function openContactModal() {
    contactPopupShow.value = true;
  }
  function closeContactModal() {
    contactPopupShow.value = false;
  }
</script>

<style lang="scss" scoped>
  .container {
    background-color: #fff;
  }
</style>
